﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AutoUpdater;
using Logging;

namespace Highlearner
{
	public partial class FormUpdate : Form
	{
		AutoUpdater.CAutoUpdater m_oUpdater = null;

		double m_dCurrentDownloadSpeed = 0;

		public FormUpdate(AutoUpdater.CAutoUpdater a_oUpdater)
		{
			m_oUpdater = a_oUpdater;
			m_oUpdater.OnDownloadStarted += new AutoUpdater.DownloadStartedDelegate(m_oUpdater_OnDownloadStarted);
			m_oUpdater.OnDownloadProgress += new AutoUpdater.DownloadProgressDelegate(m_oUpdater_OnDownloadProgress);
			m_oUpdater.OnDownloadEnded += new AutoUpdater.DownloadEndedDelegate(m_oUpdater_OnDownloadEnded);
			m_oUpdater.OnSpeedUpdated += new AutoUpdater.SpeedUpdatedDelegate(m_oUpdater_OnSpeedUpdated);

			m_oUpdater.OnError += new AutoUpdater.ErrorDelegate(m_oUpdater_OnError);

			InitializeComponent();
		}

		void m_oUpdater_OnError(string a_sMessage)
		{
			CLogger.LogMessage("Update Failed!, " + a_sMessage);
			MessageBox.Show("תהליך העדכון נכשל", "Version Update", MessageBoxButtons.OK, MessageBoxIcon.Error);
		}

		void m_oUpdater_OnDownloadEnded(long a_iFileSize)
		{
			this.Invoke(new AutoUpdater.DownloadEndedDelegate(OnDownloadEnded), a_iFileSize);
		}

		void OnDownloadEnded(long a_iFileSize)
		{
			progressBar.Value = 100;
		}

		void m_oUpdater_OnSpeedUpdated(double a_dNewSpeed)
		{
			this.Invoke(new AutoUpdater.SpeedUpdatedDelegate(OnSpeedUpdated), a_dNewSpeed);
		}

		void OnSpeedUpdated(double a_dNewSpeed)
		{
			m_dCurrentDownloadSpeed = a_dNewSpeed;
		}

		void m_oUpdater_OnDownloadProgress(long a_iBytesRead, long a_iTotal)
		{
			this.Invoke(new AutoUpdater.DownloadProgressDelegate(OnDownloadProgress), a_iBytesRead, a_iTotal);
		}

		void OnDownloadProgress(long a_iBytesRead, long a_iTotal)
		{
			progressBar.Value = (int)(((double)a_iBytesRead / (double)a_iTotal) * 100);
			labelDownloaded.Text = (a_iBytesRead / 1000).ToString("#KB");
		}

		void m_oUpdater_OnDownloadStarted(long a_iFileSize)
		{
			this.Invoke(new AutoUpdater.DownloadStartedDelegate(OnDownloadStarted), a_iFileSize);
		}

		private void OnDownloadStarted(long a_iFileSize)
		{
			label1.Visible = label2.Visible = labelDownloaded.Visible = labelSize.Visible = true;
			labelSize.Text = (a_iFileSize / 1000).ToString("#KB");
		}

		private void FormUpdate_Load(object sender, EventArgs e)
		{
			m_oUpdater.Update();
		}
	}
}
